package org.example.musicproject.service.impl;

import org.example.musicproject.dao.SingerAddsongsDao;
import org.example.musicproject.dao.impl.SingerAddsongsDaoImpl;
import org.example.musicproject.entity.SingerAddsongs;
import org.example.musicproject.service.SingerAddsongsService;
import org.example.musicproject.util.DButil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

/**
 * 创建人:黄庭萍
 * 创建时间: 2024/12/17 16:03
 * 创建类型: SingerAddsongsServiceImpl
 */
public class SingerAddsongsServiceImpl implements SingerAddsongsService {
    final SingerAddsongsDao dao = new SingerAddsongsDaoImpl();
    @Override
    public List<SingerAddsongs> all() {
        return dao.all();
    }

    @Override
    public SingerAddsongs byId(int ssid) {
        return dao.byId(ssid);
    }

    @Override
    public List<SingerAddsongs> allssid(int ssid) {
        return dao.allname(ssid);
    }

    @Override
    public long add(SingerAddsongs singerAddsongs) {
        Connection conn = DButil.getConn();
        try {
            conn.setAutoCommit(false);
            long result = dao.add(conn, singerAddsongs);
            conn.commit();
            return result;
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    throw new RuntimeException("事务回滚失败!原因:"+ex.getMessage(),ex);
                }
            }
            throw new RuntimeException("添加歌曲歌手关系绑定信息失败：" + e.getMessage(),e);
        }finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("关闭数据库连接失败:"+e.getMessage(),e);
                }
            }
        }
    }

    @Override
    public int update(SingerAddsongs singerAddsongs) {
        Connection conn = null;
        try {
            conn = DButil.getConn();
            conn.setAutoCommit(false);
            int result = dao.update(singerAddsongs);
            conn.commit();
            return result;
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException rollbackEx) {
                    throw new RuntimeException("事务回滚失败：" + rollbackEx.getMessage(), rollbackEx);
                }
            }
            throw new RuntimeException("更新歌曲歌手关系绑定信息失败：" + e.getMessage(), e);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException closeEx) {
                    throw new RuntimeException("关闭数据库连接失败：" + closeEx.getMessage(), closeEx);
                }
            }
        }
    }
}
